/**
 * wordRoutes.js
 * 单词学习相关API路由
 */

const express = require('express');
const wordController = require('../controllers/wordController');
const router = express.Router();

/**
 * 搜索单词
 * GET /api/words/search
 * 查询参数:
 *   keyword: 搜索关键词
 * 响应: { 
 *   success: boolean, 
 *   data?: { 
 *     word?: Object,    // 单个精确匹配的单词
 *     words?: Array     // 多个模糊匹配的单词列表
 *   } 
 * }
 */
router.get('/search', async (req, res) => {
  try {
    const { keyword } = req.query;
    
    if (!keyword || keyword.trim() === '') {
      return res.status(400).json({
        success: false,
        message: '请提供搜索关键词'
      });
    }
    
    const result = await wordController.searchWord(keyword);
    
    res.status(200).json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('搜索单词路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * 获取单个单词详情
 * GET /api/words/:id
 * 响应: { success: boolean, word?: Object }
 */
router.get('/:id', async (req, res) => {
  try {
    const wordId = parseInt(req.params.id);
    
    if (isNaN(wordId)) {
      return res.status(400).json({
        success: false,
        message: '无效的单词ID'
      });
    }
    
    const word = await wordController.getWordById(wordId);
    
    if (word) {
      res.status(200).json({
        success: true,
        word
      });
    } else {
      res.status(404).json({
        success: false,
        message: '单词不存在'
      });
    }
  } catch (error) {
    console.error('获取单词详情路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * 获取单词列表（支持分页和筛选）
 * GET /api/words
 * 查询参数:
 *   page: 页码，默认1
 *   pageSize: 每页数量，默认20
 *   initial: 首字母筛选，可选
 *   topic: 主题筛选，可选
 *   difficulty: 难度筛选，可选
 * 响应: { 
 *   success: boolean, 
 *   data?: { 
 *     total, 
 *     pageSize, 
 *     currentPage, 
 *     totalPages, 
 *     list 
 *   } 
 * }
 */
router.get('/', async (req, res) => {
  try {
    const { page, pageSize, initial, topic, difficulty } = req.query;
    
    const options = {
      page: parseInt(page) || 1,
      pageSize: parseInt(pageSize) || 20,
      initial,
      topic,
      difficulty: difficulty ? parseInt(difficulty) : undefined
    };
    
    const result = await wordController.getWordsList(options);
    
    res.status(200).json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('获取单词列表路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * 获取用户每日学习单词（包含新词和复习词）
 * GET /api/words/daily/:userId
 * 查询参数:
 *   newWordsLimit: 新词数量限制，可选
 *   reviewWordsLimit: 复习词数量限制，可选
 * 响应: { 
 *   success: boolean, 
 *   data?: { 
 *     newWords, 
 *     reviewWords,
 *     dailyLimits
 *   } 
 * }
 */
router.get('/daily/:userId', async (req, res) => {
  try {
    const userId = parseInt(req.params.userId);
    const { newWordsLimit, reviewWordsLimit } = req.query;
    
    if (isNaN(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }
    
    const options = {
      newWordsLimit: newWordsLimit ? parseInt(newWordsLimit) : undefined,
      reviewWordsLimit: reviewWordsLimit ? parseInt(reviewWordsLimit) : undefined
    };
    
    const result = await wordController.getDailyStudyWords(userId, options);
    
    res.status(200).json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('获取每日学习单词路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * 获取用户学习统计
 * GET /api/words/stats/:userId
 * 响应: { 
 *   success: boolean, 
 *   data?: {
 *     totalStudiedWords,
 *     masteredWords,
 *     avgMasteryLevel,
 *     avgReviewCount,
 *     totalStudyTime,
 *     streakDays,
 *     recentStudy,
 *     levelDistribution
 *   }
 * }
 */
router.get('/stats/:userId', async (req, res) => {
  try {
    const userId = parseInt(req.params.userId);
    
    if (isNaN(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }
    
    const stats = await wordController.getUserStudyStats(userId);
    
    res.status(200).json({
      success: true,
      data: stats
    });
  } catch (error) {
    console.error('获取学习统计路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * 获取用户的学习分析与建议
 * GET /api/words/analysis/:userId
 * 响应: { 
 *   success: boolean, 
 *   data?: {
 *     user: Object,
 *     summary: Object,
 *     recommendations: Object,
 *     accuracyTrend: Array
 *   }
 * }
 */
router.get('/analysis/:userId', async (req, res) => {
  try {
    const userId = parseInt(req.params.userId);
    
    if (isNaN(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }
    
    const analysisData = await wordController.analyzeUserLearningPerformance(userId);
    
    res.status(200).json({
      success: true,
      data: analysisData
    });
  } catch (error) {
    console.error('获取学习分析路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * 记录单词学习情况
 * POST /api/words/study
 * 请求体: { 
 *   userId: number, 
 *   wordId: number, 
 *   isCorrect: boolean,
 *   isNewWord: boolean
 * }
 * 响应: { 
 *   success: boolean, 
 *   data?: {
 *     mastery_level,
 *     review_stage,
 *     next_review_time,
 *     mastered
 *   }
 * }
 */
router.post('/study', async (req, res) => {
  try {
    const { userId, wordId, isCorrect, isNewWord } = req.body;
    
    if (
      userId === undefined || 
      wordId === undefined || 
      isCorrect === undefined || 
      isNewWord === undefined
    ) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    if (isNaN(userId) || isNaN(wordId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID或单词ID'
      });
    }
    
    const result = await wordController.recordWordStudy(
      parseInt(userId),
      parseInt(wordId),
      Boolean(isCorrect),
      Boolean(isNewWord)
    );
    
    res.status(200).json({
      success: true,
      data: result
    });
  } catch (error) {
    console.error('记录单词学习路由错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误',
      error: error.message
    });
  }
});

module.exports = router; 